/*
 * Copyright 2012 Tomas.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.heathtow.web.pages;

import cz.muni.fi.heathrowapi.HeathrowRoles;
import cz.muni.fi.heathrowapi.StewardService;
import cz.muni.fi.heathrowapi.dto.StewardDTO;
import cz.muni.fi.heathtow.web.auth.SecureWicketAuthenticatedWebSession;
import cz.muni.fi.heathtow.web.validation.StewardBean;
import cz.muni.fi.heathtow.web.validation.UniqueStewardIdValidator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.validation.validator.RangeValidator;

/**
 *
 * @author Tomas
 */
public class StewardView extends MainPage{

    private static final long serialVersionUID = 2L;
    
    @SpringBean(name = "stewardService")
    private StewardService stewardService;
    
    public StewardView(final PageParameters parameters) {
        super(parameters);

        showAll();
        editForm(new StewardDTO()).add(new TextField("isEdditing", Model.of("0")));
        
        Component show = new AbstractLink("showForm") {};
        add(show);
        MetaDataRoleAuthorizationStrategy.authorize(show, RENDER, HeathrowRoles.ADMIN);
        
        Label info = new Label("info", new StringResourceModel("info", this, null));
        add(info);
        info.setVisible(SecureWicketAuthenticatedWebSession.get().getRoles().equals(new Roles()));
        
        Component header = new AbstractItem("header");
        add(header);
        MetaDataRoleAuthorizationStrategy.authorize(header, RENDER, HeathrowRoles.USER);
    }

    public StewardView(PageParameters parameters, StewardDTO stew) {
        super(parameters);
        showAll();
        editForm(stew).add(new TextField("isEdditing", Model.of("1")));

        Component show = new AbstractLink("showForm") {};
        add(show);
        MetaDataRoleAuthorizationStrategy.authorize(show, RENDER, HeathrowRoles.ADMIN);
        
        Label info = new Label("info", new StringResourceModel("info", this, null));
        add(info);
        info.setVisible(SecureWicketAuthenticatedWebSession.get().getRoles().equals(new Roles()));
        
        Component header = new AbstractItem("header");
        add(header);
        MetaDataRoleAuthorizationStrategy.authorize(header, RENDER, HeathrowRoles.USER);
    }

    private void showAll() {
        

        final RepeatingView repeatingView = new RepeatingView("repeating");
        MetaDataRoleAuthorizationStrategy.authorize(repeatingView, RENDER, HeathrowRoles.USER);
        add(repeatingView);

        Label connectionError = new Label("error", new StringResourceModel("error", this, null));
        add(connectionError);
        connectionError.setVisible(false);
        
        try {
            for (final StewardDTO stew : stewardService.findAll()) {
                AbstractItem item = new AbstractItem(repeatingView.newChildId());

                item.add(new Label("contactID", String.valueOf(stew.getId())));
                item.add(new Label("firstname", stew.getFirstName()));
                item.add(new Label("lastname", stew.getLastName()));
                item.add(new Label("personalID", String.valueOf(stew.getPersonalId())));
                Link edit = new Link("pensLink") {
                    @Override
                    public void onClick() {
                        setResponsePage(new StewardView(new PageParameters(),stew));
                    }
                };
                MetaDataRoleAuthorizationStrategy.authorize(edit, RENDER, HeathrowRoles.ADMIN);
                item.add(edit);
                
                Link delete = new Link("crossLink") {
                    @Override
                    public void onClick() {
                        stewardService.remove(stew);
                        setResponsePage(new StewardView(new PageParameters()));
                    }
                };
                MetaDataRoleAuthorizationStrategy.authorize(delete, RENDER, HeathrowRoles.ADMIN);
                item.add(delete);
                

                repeatingView.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(DestinationView.class.getName()).log(Level.SEVERE, null, ex);
            connectionError.setVisible(!SecureWicketAuthenticatedWebSession.get().getRoles().equals(new Roles()));
        }

        

    }

    private Form editForm(final StewardDTO steward) {
        
        final FeedbackPanel feedback = new FeedbackPanel("feedback");
        feedback.setOutputMarkupId(true);
        add(feedback);
        
        StewardBean bean= new StewardBean();
        Form<StewardBean> form = new Form<StewardBean>("stewForm", new CompoundPropertyModel<StewardBean>(bean));
        add(form);
        form.setOutputMarkupId(true);
        
        FormComponent<String> firstNameField = new RequiredTextField("firstnameForm", new PropertyModel<String>(steward, "firstName")); 
        firstNameField.setLabel(new ResourceModel("form.firstname"));
        
        FormComponent<String> lastNameField = new RequiredTextField("lastnameForm", new PropertyModel<String>(steward, "lastName")); 
        lastNameField.setLabel(new ResourceModel("form.lastname"));
        
        FormComponent<Long> idField = new RequiredTextField("personalIDForm", new PropertyModel<Long>(steward, "personalId")).add(RangeValidator.range(Long.MIN_VALUE, Long.MAX_VALUE));
        idField.add(new UniqueStewardIdValidator(steward.getId()));
        idField.setLabel(new ResourceModel("form.personalID"));
        
        AjaxButton sumbitButton = new AjaxButton("submitButton") {
            @Override
            public void onSubmit(AjaxRequestTarget target, Form<?> form) {
               if (steward.getId() == null) {
                    stewardService.create(steward);
                    setResponsePage(new StewardView(new PageParameters()));
                } else {
                    stewardService.update(steward);
                    setResponsePage(new StewardView(new PageParameters()));
                }
            }
            
            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.add(feedback);
            }
        };

        Button cancelButton = new Button("cancelButton") {
            @Override
            public void onSubmit() {
                setResponsePage(new StewardView(new PageParameters()));
            }
        };
        cancelButton.setDefaultFormProcessing(false); 


        form.add(firstNameField, lastNameField, idField, sumbitButton, cancelButton);
        form.add(new Label("heading", new StringResourceModel(steward.getId() == null ? "form.addHeading" : "form.editHeading", this, null)));

        AjaxFormValidatingBehavior.addToAllFormComponents(form, "onkeyup", Duration.ONE_SECOND);        
        
        return form;
    }
}